<template>
  <div class="user-favorites">
    <el-card class="favorite-card">
      <template #header>
        <div class="card-header">
          <h3>我的收藏</h3>
          <el-button type="primary" @click="handleBatchDelete" v-if="selectedItems.length">
            批量删除
          </el-button>
        </div>
      </template>

      <div class="favorite-list" v-loading="loading">
        <el-empty v-if="!favoriteList.length" description="暂无收藏商品" />
        
        <el-row :gutter="20" v-else>
          <el-col :span="6" v-for="item in favoriteList" :key="item.id">
            <el-card class="product-card" :body-style="{ padding: '0px' }">
              <div class="checkbox-wrapper" @click.stop>
                <el-checkbox v-model="item.selected" @change="handleSelect" />
              </div>
              
              <el-image 
                :src="item.image" 
                fit="cover"
                class="product-image"
                @click="goToProduct(item)"
              />
              
              <div class="product-info">
                <h4 class="product-name" @click="goToProduct(item)">
                  {{ item.name }}
                </h4>
                <div class="price-action">
                  <span class="price">¥{{ item.price }}</span>
                  <el-button 
                    type="danger" 
                    size="small" 
                    circle
                    @click="handleDelete(item)"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 分页 -->
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[12, 24, 36, 48]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import { getUserFavoriteList, cancelFavorite } from '@/api/favorite'

const router = useRouter()

// 状态数据
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)
const favoriteList = ref([])

// 计算选中的商品
const selectedItems = computed(() => {
  return favoriteList.value.filter(item => item.selected)
})

// 获取收藏列表
const getFavoriteList = async () => {
  loading.value = true;
  try {
    // 调用后端接口获取收藏列表
    const res = await getUserFavoriteList();
    // 适配接口返回结构，从spuVO中提取商品信息，并添加selected字段
    const allFavorites = res.map(item => ({
      // 保留收藏记录的ID，可能用于将来的取消收藏接口（如果后端需要）
      // 但根据你提供的取消收藏接口，只需spuId
      id: item.id, // 收藏记录ID
      spuId: item.spuId, // 商品SPU ID
      name: item.spuVO?.title || '未知商品', // 从spuVO获取商品名称
      image: item.spuVO?.mainImage || '', // 从spuVO获取商品主图
      price: item.spuVO?.price || 0, // 从spuVO获取商品价格
      selected: false // 用于前端批量操作
    }));

    total.value = allFavorites.length;
    // 前端分页处理
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    favoriteList.value = allFavorites.slice(start, end);

  } catch (error) {
    console.error('获取收藏列表失败：', error);
    ElMessage.error('获取收藏列表失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 跳转到商品详情
const goToProduct = (item) => {
  router.push({
    name: 'GoodsDetail',
    query: { id: item.spuId }
  })
}

// 删除单个收藏
const handleDelete = (item) => {
  ElMessageBox.confirm('确定要取消收藏该商品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 调用取消收藏接口，传入spuId
      await cancelFavorite(item.spuId);
      ElMessage.success('取消收藏成功');
      getFavoriteList(); // 刷新列表
    } catch (error) {
      console.error('取消收藏失败：', error);
      ElMessage.error('取消收藏失败，请重试');
    }
  });
};

// 批量删除收藏
const handleBatchDelete = () => {
  // 获取选中商品的spuId数组
  const spuIds = selectedItems.value.map(item => item.spuId);
  ElMessageBox.confirm(`确定要取消收藏选中的${spuIds.length}件商品吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // TODO: 根据后端批量取消收藏接口修改这里的调用
      // 如果批量接口支持 spuId 数组，可以这样调用：
      // await batchCancelFavorite(spuIds);
      // 如果没有批量接口，需要循环调用单个取消接口：
      for (const spuId of spuIds) {
         await cancelFavorite(spuId);
      }

      ElMessage.success('批量取消收藏成功');
      getFavoriteList(); // 刷新列表
    } catch (error) {
      console.error('批量取消收藏失败：', error);
      ElMessage.error('批量取消收藏失败，请重试');
    }
  });
};

// 选择商品
const handleSelect = () => {
  // 更新选中状态，不需要特殊处理
}

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val
  getFavoriteList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getFavoriteList()
}

// 初始化
onMounted(() => {
  getFavoriteList()
})
</script>

<style scoped>
.user-favorites {
  width: 100%;
}

.favorite-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
}

.product-card {
  margin-bottom: 20px;
  position: relative;
  transition: all 0.3s;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.checkbox-wrapper {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 1;
  background-color: rgba(255,255,255,0.9);
  border-radius: 50%;
  padding: 5px;
}

.product-image {
  width: 100%;
  height: 200px;
  cursor: pointer;
}

.product-info {
  padding: 14px;
}

.product-name {
  margin: 0;
  font-size: 14px;
  cursor: pointer;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-height: 1.5;
  height: 42px;
}

.product-name:hover {
  color: var(--el-color-primary);
}

.price-action {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.price {
  color: var(--el-color-danger);
  font-size: 18px;
  font-weight: bold;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>